"use strict";
// 获取请求地址
var requestType = "request";
// 应用版本
var version = "10.0.3";
//页面展示条数
var rows = 20;
var userInfo = null;
var systemName = "ios";
var WeiXinOauth = true;

function http_build_query(formdata, url) { // eslint-disable-line camelcase
	//  discuss at: http://locutus.io/php/http_build_query/
	// original by: Kevin van Zonneveld (http://kvz.io)
	// improved by: Legaev Andrey
	// improved by: Michael White (http://getsprink.com)
	// improved by: Kevin van Zonneveld (http://kvz.io)
	// improved by: Brett Zamir (http://brett-zamir.me)
	//  revised by: stag019
	//    input by: Dreamer
	// bugfixed by: Brett Zamir (http://brett-zamir.me)
	// bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
	//      note 1: If the value is null, key and value are skipped in the
	//      note 1: http_build_query of PHP while in locutus they are not.
	//   example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;')
	//   returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
	//   example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_')
	//   returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk'

	var value, key, tmp = [], argSeparator = '&';

	var _httpBuildQueryHelper = function (key, val, argSeparator) {
		var k, tmp = [];
		if (val === true) {
			val = '1';
		} else if (val === false) {
			val = '0';
		}
		if (val !== null) {
			if (typeof val === 'object') {
				for (k in val) {
					if (val[k] !== null) {
						tmp.push(_httpBuildQueryHelper(key + '[' + k + ']', val[k], argSeparator));
					}
				}
				return tmp.join(argSeparator);
			} else if (typeof val !== 'function') {
				return encodeURIComponent(key) + '=' + encodeURIComponent(val);
			} else {
				throw new Error('There was an error processing for http_build_query().');
			}
		} else {
			return '';
		}
	};

	if (!argSeparator) {
		argSeparator = '&';
	}
	for (key in formdata) {
		value = formdata[key];
		var query = _httpBuildQueryHelper(key, value, argSeparator);
		if (query !== '') {
			tmp.push(query);
		}
		url = url.replace(new RegExp(key + '=[^&#]*&?', 'ig'), '');
	}

	url && (url = url.replace(/[&?]+$/, ''));
	var paramString = tmp.join(argSeparator);
	var result = !url ? '' : url + (!paramString ? '' : (url.indexOf('?') != -1 ? '&' : '?'));
	result += paramString;
	return result;
}

// 是否在微信内
function inWechat() {
	return navigator.userAgent.match(/MicroMessenger/i);
}

if(inWechat()) {
	version = '99.9.9';
}

// 获取本地存储用户信息
function getLocalUserInfo() {
	let result = localCache('user_info');
	if(!result || !result.user_id) {
		result = null;
		setLocalUserInfo('');
	}
	if (result) {
		setLocalUserInfo(result);
	}
	return result;
}

// 设置本地存储用户信息
function setLocalUserInfo(info) {
	userInfo = info;
	localCache('user_info', info, 1);
}

// 初始化用户信息
userInfo = getLocalUserInfo();

function isPlusReady() {
	return typeof plus !== 'undefined';
}

// APP 更新
function appUpdate(url) {
	if (window.app_downloading || !isPlusReady()) return;
	window.app_downloading = true;
	mui.alert('做了一些体验优化，使用更加顺手。', '发现新版本', '立即更新', function (e) {
		var wgtWaiting = plus.nativeUI.showWaiting('下载更新中，请勿关闭');
		var dtask = plus.downloader.createDownload(url, {}, function (d, status) {
			window.app_downloading = false;
			if (status == 200) { // 下载成功
				var path = d.filename;
				plus.runtime.install(path);
				mui.alert('新版本已下载。', '版本更新', '立即安装', function (e) {
					plus.runtime.install(path);
				});
			} else { //下载失败
				mui.toast("Download failed: " + status);
			}
		});

		dtask.addEventListener("statechanged", function (download, status) {
			switch (download.state) {
				case 2:
					wgtWaiting.setTitle("已连接到服务器");
					break;
				case 3:
					var percent = download.downloadedSize / download.totalSize * 100;
					wgtWaiting.setTitle("已下载 " + parseInt(percent) + "%");
					break;
				case 4:
					wgtWaiting.setTitle("下载完成");
					wgtWaiting.close();
					break;
			}
		});
		dtask.start();
	});

}

var baseApi = {};
mui.each(['get', 'post'], function (index, method) {
	baseApi[method] = function (params, callback, errorCallBack) {
		try {
			if (userInfo) {
				params.uid = userInfo.user_id;
				params.system = systemName;
			}
			if (typeof params === 'object') {
				params = {
					alert: 1,
					version: version,
					p: JSON.stringify(params)
				};

				console.log(JSON.stringify(params));
			}

			if (!isHaveNet()) {
				mui.toast("网络连接失败！请检查网络连接！");
				return;
			}

			if (isPlusReady()) plus.nativeUI.showWaiting();
			// console.log('Request => ' + JSON.stringify(params));
			params = {
				url: getRequestAddressUrl('base'),
				type: method.toUpperCase(),
				data: params,
				dataType: 'json',
				beforeSend: function () {
				},
				error: function (res) {
				},
				success: function (result) {
					if (isPlusReady()) plus.nativeUI.closeWaiting();
					// console.log(JSON.stringify(result));
					if (result.status == 0) {
						if (errorCallBack) {
							errorCallBack();
						}
						mui.toast(result.result);
					} else if (result.status == 9) {
						// 下载更新
						appUpdate(result.result);
					} else if (result.status == 1) {
						return callback(result.result);
					} else {
						mui.toast('异常错误');
					}
				},
				complete: function (result) {
					// window.form_submitted = false;
					// return completeCallback(result);
				}
			}
			return $.ajax(params);
		} catch (e) {
		}
	};
});

// 页面跳转
$('.open-url').on('tap', function () {
	var url = $(this).is('a') ? $(this).attr('href') : $(this).data('url');
	var data = $(this).data();
	var params = JSON.parse(JSON.stringify(data || {}));
	delete params.url;
	delete params.href;

	// 缓存
	params._random = Math.random();

	pageChange(url, params);
	return false;
});

// 图片的请求地址
//var filesHost = getRequestAddressUrl("filesHost");
var loginid = window.localStorage.getItem("uid");
//var loginid = "1000171372";

// 是否为免登陆页面
function isLoginFreePage() {
	return /(login|register|forgot_passwd)/.test(location.href);
}

// 检查登陆状态
function checkUserLogin() {
	if (!userInfo && !isLoginFreePage()) {
		pageChange("../user/login.html", {
			referer: location.href
		});
	}
}

// 关闭所有页面
function clearAllWindows() {
	var all = plus.webview.all();
	for (key in all) {
		if (all[key] !== plus.webview.currentWebview()) {
			plus.webview.close(all[key]);
		}
	}
}

// 关闭当前页面
function closeCurrentWindow() {
	if (isPlusReady()) {
		plus.webview.close(plus.webview.currentWebview());
	} else {
		history.go(-1);
	}
}

// 退出登录
function userLogout() {
	userInfo = null;
	setLocalUserInfo('');
	checkUserLogin();
}

// 用户信息更新
function userInfoUpdate(info) {
	if (info) {
		setLocalUserInfo(info);
	} else {
		baseApi.post({
			op: 'getuserinfo'
		}, function (result) {
			setLocalUserInfo(result);
		});
	}
}

mui.plusReady(function () {
	console.log(JSON.stringify(userInfo));
	// 存储父页面webViewId
	if (mui("#parentWebViewId").length == 0) {
		var inputBox = document.createElement('input');
		inputBox.id = "parentWebViewId";
		inputBox.style.display = "none";
		inputBox.type = "text"
		inputBox.value = (getQueryString("webViewId")) ? getQueryString("webViewId") : "";
		document.body.appendChild(inputBox);
	} else {
		mui("#parentWebViewId")[0].value = (getQueryString("webViewId")) ? getQueryString("webViewId") : "";
	}
});
//changeWindowWidth();

var cssEl = document.createElement('style');
document.documentElement.firstElementChild.appendChild(cssEl);

function setPxPerRem(clientWidth) {
	var dpr = 1;
	//把viewport分成15份的rem，html标签的font-size设置为1rem的大小;

	if (!clientWidth) {
		clientWidth = document.documentElement.clientWidth;
	}

	var pxPerRem = clientWidth * dpr / 15;
	cssEl.innerHTML = 'html{font-size:' + pxPerRem + 'px!important;}';
}

var clientWidth = 0;
var clientHeight = 0;

function changeWindowWidth() {
	if (!clientWidth) {
		clientWidth = document.documentElement.clientWidth;
		clientHeight = document.documentElement.clientHeight;
	}
	if (navigator.platform.indexOf("Win32") || clientHeight < clientWidth) {
		document.getElementsByTagName("body")[0].style.width = "320px";
	} else {
		document.getElementsByTagName("body")[0].style.width = clientWidth + "px";
	}

}

// 处理横屏竖屏事件
var evt = "onorientationchange" in window ? "orientationchange" : "resize";
window.addEventListener(evt, function () {
	// 竖屏
	if (window.orientation === 180 || window.orientation === 0) {
		if (typeof orientation180 == "function") {
			orientation180();
		}
	}
	// 横屏
	if (window.orientation === 90 || window.orientation === -90) {
		if (typeof orientation90 == "function") {
			orientation90();
		}
	}
}, false);
// 是否竖屏显示
// flg：true竖屏显示
function lockOrientation(flg) {
	if (flg) {
		plus.screen.lockOrientation("portrait-primary");
	}
}

// mui全局处理
mui.init({
	beforeback: function () {
		// 页面回调方法
		if (typeof beforeback === 'function') {
			beforeback.call();
		}
	}
});

// 设置json默认值
// defaults：默认值
// settings：返回值
function extendSettings(defaults, settings) {
	if (typeof(settings) != "object") {
		return defaults;
	} else {
		for (var o in defaults) {
			var addflg = true;
			var addobj;
			for (var n in settings) {
				if (o == n) {
					addflg = false;
					addobj = "";
					break;
				} else {
					addobj = o;
				}
			}

			if (addflg) {
				settings[addobj] = defaults[addobj];
			}
		}

		return settings;
	}
}

// 事件绑定
// settings.eventId：对象id
// settings.eventType：事件绑定类型，默认tap
// settings.eventFunction：触发方法体
function elementBindEvent(settings) {
	var defaults = {
		eventType: "tap"
	};
	settings = extendSettings(defaults, settings);
	mui("#" + settings.eventId)[0].addEventListener(settings.eventType, function () {
		if (settings.eventFunction) {
			settings.eventFunction.call('', this);
		}
	})
};
// 群组上事件
// settings.eventObj：父容器id
// settings.eventType：事件绑定类型
// settings.targetObj：带绑定控件组样式
// settings.eventFunction：触发方法体
function elementBindEventByObj(settings) {
	var defaults = {
		eventType: "tap"
	};
	settings = extendSettings(defaults, settings);
	mui("#" + settings.eventObj).on(settings.eventType, "." + settings.targetObj, function () {
		if (settings.eventFunction) {
			settings.eventFunction.call('', this);
		}
	})
};


// 关闭登录 webview
function closeWebview(pageID, duration, delay) {
	console.log(pageID);
	console.log(pageID.id);
	setTimeout(function () {
		plus.webview.close(pageID, null, duration || 0);
	}, delay || 0)
}

window.pageReload = function () {
};

// 页面跳转
// url：页面url
// params：目标页面参数
// backend：是否是后台加载
function pageChange(url, params, backend) {
	// pagechange 之后不允许重置任务栏
	window.statusBarResetDisabled = true;

	params = params || {};
	var pageID = url.replace(/^.*\/((\w+)\/(\w+))\.html.*$/, '$1');
	// 记录登录前的页面
	if (pageID === 'member/login_mobile') {
		localCache('login_prev_page', {
			page_id: location.href.replace(/^.*\/([^\/]+\/[^\/]+)\.html.*$/, '$1'),
			params: getQueryString()
		});
	}

	// 正式环境去除 js 跳转
	// if(typeof plus === 'undefined') {
	// 	setTimeout(function () {
	// 		pageChange(url, params, backend);
	// 	}, 100);
	// 	return;
	// }

	params._random = Math.random();

	if (!url) return;    // 链接为空

	url = http_build_query(params, url);
	if (typeof plus === 'undefined') {
		location.href = url;
	} else {
		// 如果是主页，直接显示
		var aniShow = 'slide-in-right';

		// 如果是主页，刷新页面
		var wb = plus.webview.getWebviewById(pageID);

		if (wb && isIndexPage(url)) {
			// 检查地址是否正确
			if ((new RegExp(pageID)).test(wb.getURL())) {
			} else {
				wb.loadURL(url);
			}
			aniShow = 'none';
			plus.webview.show(pageID, aniShow, 300, function () {
				wb.evalJS('pageReload(' + JSON.stringify(params) + ');');
			});
			return;
		} else if (wb) {
			// 打开新页面，关闭旧页面
			closeWebview(wb, 0, 1000);
		}

		let style = {};

		let nw = mui.openWindow({
			id: pageID,
			url: url,
			show: {
				autoShow: !backend, //页面loaded事件发生后自动显示，默认为true
				aniShow: aniShow, //页面显示动画，默认为”slide-in-right“；
				duration: 300 //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
			},
			styles: style,
			createNew: true,
			waiting: {
				autoShow: false
			},
			extras: {params: params}
		});

		nw.addEventListener('close', function (e) {
			window.statusBarResetDisabled = false;
			// 改变 statusbar 颜色，背景颜色
			// 上级页面数据重新加载
			window.pageReload();
		}, false);
	}
};
// 获取请求参数
// name：参数名称
function getQueryString(name) {
	// 只从 url 里获取参数
	if (false && typeof plus !== 'undefined') {
		let self = plus.webview.currentWebview();
		let params = self.params;
		if (name) {
			var value = params[name];
			if (isEmpty(value)) {
				value = ""
			}
			return decodeURIComponent(value);
		} else {
			return params;
		}
	} else {
		if (name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) return decodeURIComponent(r[2]);
			return '';
		} else {
			let params = window.location.search.substr(1).split('&');
			var query = {};
			for (var i = 0; i < params.length; i++) {
				if (params[i]) {
					var arr = params[i].split('=');
					query[arr[0]] = decodeURIComponent(arr[1]);
				}
			}
			return query;
		}
	}
}

function addCookie(e, t, a) {
	return localCache(e, t, a);
}

// 本地缓存查询及设置
function localCache(key, data, t) {
	t = (t || 1) * (86400 * 1000);	// 默认缓存1天

	key = 'DATA_CACHE_' + key;
	if (t < 0) {
		localStorage.removeItem(key);
	}
	// 取值
	else if (typeof data === 'undefined') {
		var cache = localStorage.getItem(key);
		if (cache && cache !== 'undefined') {
			cache = JSON.parse(cache);
			if (cache.expire > (new Date).getTime()) {
				return cache.data;
			}
		}
		return '';
	}
	else {
		var cache = {
			expire: (new Date).getTime() + t,
			data: data
		};

		cache = JSON.stringify(cache);
		localStorage.setItem(key, cache);
	}

}

function setCookie(name, value, days) {
	return localCache(name, value, days);
}

function getCookie(name) {
	return localCache(name);
}

function delCookie(name) {
	return localCache(name, null, -1);
}

//生成32位随机码
function newGuid() {
	var guid = "";
	for (var i = 1; i <= 32; i++) {
		var n = Math.floor(Math.random() * 16.0).toString(16);
		guid += n;
	}
	return guid;
};

// 获取请求地址
function getRequestAddressUrl(addKey) {
	var retUrl = "";
	for (var i = 0; i < requestAddressList.length; i++) {
		if (requestAddressList[i].addressKey == addKey) {
			retUrl = requestAddressList[i].url;
			break;
		}
	}

	return retUrl;
};

// 组合json
function jsonjoin(sorJosn, tarJosn) {
	sorJosn.push = function (o) {
		if (typeof(o) == 'object')
			for (var p in o) this[p] = o[p];
	};
	sorJosn.push(
		tarJosn
	)

	return sorJosn;
};
// 调用父webview方法
// funName：方法名
// params：参数
function callParentWebViewFun(funName, params) {
	if (!params) {
		params = {};
	}
	var pageid = mui("#parentWebViewId")[0].value;
	mui.fire(plus.webview.getWebviewById(pageid), funName, params);
};

// 请求方法
// settings.url：请求路径
// settings.appurl：json请求路径
// settings.pastDate：参数json格式
// settings.addressKey：请求地址key，默认request
// settings.nativeFlg:是否为原生，默认false
// settings.requestType:POST GET 默认GET
// settings.addressUrl:请求地址，默认请求地址为 requestType  loginType-登陆   appType -应用中心  addFriend 即时通讯加好友
// settings.getapp  根据当前登录人身份获取应用  app
// callBackFun：回调方法
function crossDomainAjax(settings, callBackFun) {
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var defaults = {
		addressKey: "request",
		nativeFlg: false
	};
	if (!settings.addressUrl) {
		settings.addressUrl = "requestType";
	}
	if (!settings.appurl) {
		settings.appurl = settings.url;
	}
	if (!settings.requestType) {
		settings.requestType = "GET";
	}
	settings = extendSettings(defaults, settings);
	var temp = new Date().getTime();
	var requestUrl;
	if (requestType == "request") {
		var temp = new Date().getTime();
		if (settings.addressUrl == 'loginType') {
			requestUrl = getRequestAddressUrl("login");
		} else if (settings.addressUrl == 'appType') {
			requestUrl = getRequestAddressUrl("appType") + settings.url;
		} else if (settings.addressUrl == 'testline') {
			requestUrl = getRequestAddressUrl("testline") + settings.url;
		} else if (settings.addressUrl == 'resourceCentre') {
			requestUrl = getRequestAddressUrl("resourceCentre") + settings.url;
		} else {
			requestUrl = getRequestAddressUrl(requestType) + settings.url;
		}
	} else {
		requestUrl = appurl + settings.appurl;
	}
	if (settings.requestType == 'GET') {
		// 处理请求缓存
		if (requestUrl.indexOf('?') != -1) {
			requestUrl = requestUrl + "&time=" + temp + "&v=" + version;
		} else {
			requestUrl = requestUrl + "?time=" + temp + "&v=" + version;
		}
		// 处理参数
		for (var o in settings.pastDate) {
			requestUrl = requestUrl + "&" + o + "=" + settings.pastDate[o];
		}
	}
	console.log("requestUrl--》" + requestUrl);
	if (!settings.nativeFlg || (settings.nativeFlg && requestType == "request")) {
		var appAjax = new XMLHttpRequest();
		appAjax.open(settings.requestType, requestUrl, true);

		if (!isEmpty(settings.authorization)) {
			logText("settings.authorization==>" + settings.authorization)
			appAjax.setRequestHeader('authorization', settings.authorization)
		}

		if (settings.requestType == "GET") {
			if (!isEmpty(settings.getapp)) {
				appAjax.setRequestHeader("Wd-Token", window.localStorage.getItem("Wd-Token"));
			}
			appAjax.send("");
		} else if (settings.requestType == "POST") {
			appAjax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
			var jsonData = JSON.stringify(settings.pastDate);
			appAjax.send(jsonData);
		}
		appAjax.onreadystatechange = function () {
			if (appAjax.readyState == 4) {
				var responseDate = JSON.parse(appAjax.responseText);
				if (callBackFun) {
					callBackFun.call('', responseDate);
				}
				appAjax = null;
			}
		}
	} else {
		var jsonDataUrl = requestUrl;
		plus.io.requestFileSystem(plus.io.PRIVATE_WWW, function (fs) {
			fs.root.getFile(jsonDataUrl, {
				create: true
			}, function (fileEntry) {
				fileEntry.file(function (file) {
					var fileReader = new plus.io.FileReader();
					fileReader.readAsText(file, 'utf-8');
					fileReader.onloadend = function (evt) {
						var responseDate = eval("(" + evt.target.result + ")");
						if (callBackFun) {
							callBackFun.call('', responseDate);
						}
					}
				});
			});
		});
	}
}

// 获取相邻元素(内部方法)
function getNearEle(ele, type) {
	type = type == 1 ? "previousSibling" : "nextSibling";
	var nearEle = ele[type];
	while (nearEle) {
		if (nearEle.nodeType === 1) {
			return nearEle;
		}
		nearEle = nearEle[type];
		if (!nearEle) {
			break;
		}
	}
	return null;
}

// 获取当前对象的上一个元素
// ele：当前对象
function prev(ele) {
	return getNearEle(ele, 1);
}

// 获取当前对象的下一个元素
// ele：当前对象
function next(ele) {
	return getNearEle(ele, 0);
}

// 获得匹配元素集合中每个元素前面的所有同胞元素
// ele：当前对象
// tarEle：查询的对象类型
function prevAll(ele, tarEle) {
	var prevEles = [];
	var ele = getNearEle(ele, 1);
	return pushEle(prevEles, ele, tarEle);

	function pushEle(prevEles, ele, tarEle) {
		if (ele) {
			if (tarEle) {
				if (ele.nodeName.toLowerCase() == tarEle || ele.className.indexOf(tarEle) != -1 || ele.id == tarEle) {
					prevEles.push(ele);
					ele = getNearEle(ele, 1);
					pushEle(prevEles, ele, tarEle);
				} else {
					ele = getNearEle(ele, 1);
					pushEle(prevEles, ele, tarEle);
				}
			} else {
				prevEles.push(ele);
				ele = getNearEle(ele, 1);
				pushEle(prevEles, ele, tarEle);
			}
		}
		return prevEles;
	}
}

// 获得匹配元素集合中每个元素的所有跟随的同胞元素
// ele：当前对象
// tarEle：查询的对象类型
function nextAll(ele, tarEle) {
	var nextEles = [];
	var ele = getNearEle(ele, 0);
	return pushEle(nextEles, ele, tarEle);

	function pushEle(nextEles, ele, tarEle) {
		if (ele) {
			if (tarEle) {
				if (ele.nodeName.toLowerCase() == tarEle || ele.className.indexOf(tarEle) != -1 || ele.id == tarEle) {
					nextEles.push(ele);
					ele = getNearEle(ele, 0);
					pushEle(nextEles, ele, tarEle);
				} else {
					ele = getNearEle(ele, 0);
					pushEle(nextEles, ele, tarEle);
				}
			} else {
				nextEles.push(ele);
				ele = getNearEle(ele, 0);
				pushEle(nextEles, ele, tarEle);
			}
		}
		return nextEles;
	}
}

// 当前对象前插入元素、newEle放到tarEle前面
function insertBefore(newEle, tarEle) {
	var parent = tarEle.parentNode;
	if (!parent) {
		parent = tarEle;
	}
	parent.insertBefore(newEle, tarEle);
}

// 当前对象后插入元素、newEle放到tarEle后面
function insertAfter(newEle, tarEle) {
	var parent = tarEle.parentNode;
	if (!parent) {
		parent = tarEle;
	}
	if (parent.lastChild == tarEle) {
		parent.appendChild(newEle);
	} else {
		parent.insertBefore(newEle, tarEle.nextSibling);
	}
}

// 获取指定元素 ele.find(tarEle)
function find(ele, tarEle) {
	var tarEles = [];
	var nodes = ele.childNodes;
	return getEle(tarEles, nodes, tarEle);

	function getEle(tarEles, nodes, tarEle) {
		for (var i = 0; i < nodes.length; i++) {
			if (nodes[i].nodeName.toLowerCase() == tarEle || nodes[i].className == tarEle || nodes[i].id == tarEle) {
				tarEles.push(nodes[i]);
				getEle(tarEles, nodes[i].childNodes, tarEle);
			} else {
				getEle(tarEles, nodes[i].childNodes, tarEle);
			}
		}
		return tarEles;
	}
}

// 获取元素位置
// tarEle：当前元素
function index(tarEle) {
	var parent = tarEle.parentNode;
	var eleArr = parent.childNodes;
	var index = 0;
	for (var i = 0; i < eleArr.length; i++) {
		if (eleArr[i] == tarEle) {
			index = i;
			break;
		}
	}
	return index;
}

// 移除元素
// ele:当前元素
function remove(ele) {
	var parent = ele.parentNode;
	parent.removeChild(ele);
}

// 循环数组
function foreach(array, func) {
	for (var i = 0; i < array.length; ++i) {
		func(array[i]);
	}
};

// 滚动到对象底部
function scrollBottom(obj) {
	obj.scrollTop = obj.scrollHeight;
}

// 加载模板H5用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//templateUrl:模板配置文件名称，命名规范"template_模块名_页面模板名称（可选）",注：不用传文件后缀
//templateId:需要模板展现的父容器id
//loadFunction:模板加载完成后回调方法
//parameters：回调方法参数
function getTemplate(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('-')[0].toLowerCase();
	var languageData;
	var appAjaxLanguage = new XMLHttpRequest();
	appAjaxLanguage.open('GET', appurl + settings.languageUrl + "_" + languageType + ".properties", true);
	appAjaxLanguage.send(null);
	appAjaxLanguage.onreadystatechange = function () {
		if (appAjaxLanguage.readyState == 4) {
			languageDate = eval("(" + appAjaxLanguage.responseText + ")");
			localStorage[settings.languageUrl] = appAjaxLanguage.responseText;
			var appAjax = new XMLHttpRequest();
			appAjax.open('GET', appurl + settings.templateUrl + ".html", true);
			appAjax.send(null);
			appAjax.onreadystatechange = function () {
				if (appAjax.readyState == 4) {
					var responseData = appAjax.responseText;

					responseData = changenDataByLanguage(responseDate, languageData);

					document.getElementById(settings.templateId).innerHTML = responseData;

					if (settings.loadFunction) {
						settings.loadFunction.call(null, settings.parameters, languageData);
					}
					appAjax = null;
				}
			}

			appAjaxLanguage = null;
		}
	}
};
// 获取国际化信息原生用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//languageData：返回国际化信息（json格式）
function getLanguageDataNative(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('_')[0].toLowerCase();
	var languageUrl = appurl + settings.languageUrl + "_" + languageType + ".properties";

	plus.io.requestFileSystem(plus.io.PRIVATE_WWW, function (fs) {
		fs.root.getFile(languageUrl, {
			create: true
		}, function (fileEntry) {
			fileEntry.file(function (file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = function (evt) {
					localStorage[settings.languageUrl] = evt.target.result;
				};
			});
		});
	});
	setTimeout(function () {
		settings.languageDataFn.call('', getLanguageDataAgain(settings.languageUrl, settings));
	}, 100)

};
// 单独获取国际化信息
//key:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//languageData：返回国际化信息（json格式）
function getLanguageDataAgain(key, settings) {
	//	console.log("key"+key);
	if (localStorage[key] != "") {
		return eval("(" + localStorage[key] + ")");
	} else {
		return getLanguageDataNative(settings);
	}
}

// 加载模板原生用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//templateUrl:模板配置文件名称，命名规范"template_模块名_页面模板名称（可选）",注：不用传文件后缀
//templateId:需要模板展现的父容器id
//loadFunction:模板加载完成后回调方法
//parameters：回调方法参数
function getTemplateNative(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('_')[0].toLowerCase();
	var languageUrl = appurl + settings.languageUrl + "_" + languageType + ".properties";
	var templateUrl = appurl + settings.templateUrl + ".html";

	plus.io.requestFileSystem(plus.io.PRIVATE_WWW, function (fs) {
		fs.root.getFile(languageUrl, {
			create: true
		}, function (fileEntry) {
			fileEntry.file(function (file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = function (evt) {
					var languageData = eval('(' + evt.target.result + ')');
					localStorage[settings.languageUrl] = evt.target.result;
					fs.root.getFile(templateUrl, {
						create: true
					}, function (fileEntry) {
						fileEntry.file(function (file) {
							var fileReader = new plus.io.FileReader();
							fileReader.readAsText(file, 'utf-8');
							fileReader.onloadend = function (evt) {
								var responseData = changenDataByLanguage(evt.target.result, languageData);
								document.getElementById(settings.templateId).innerHTML = responseData;

								if (settings.loadFunction) {
									settings.loadFunction.call(null, settings.parameters, languageData);
								}
							}
						})
					})
				}
			});
		});
	});
}

// 替换语言信息
function changenDataByLanguage(responseData, languageData) {
	for (var o in languageData) {
		responseData = responseData.replace(new RegExp("\\{{" + o + "\\}}", "g"), languageData[o]);
	}
	return responseData;
}

//格式化时间 服务器返回时间格式为yyyyMMddHHmmssSSS 17位字符串
//将服务器时间修改为yyyy-MM-dd HH:mm 的基本格式
function formatCreateTimeByBase(createTime) {
	if (!createTime) {
		console.log("时间传入值为空。");
		return;
	}
	if (createTime.length > 12) {
		var year = createTime.slice(0, 4);
		var month = createTime.slice(4, 6);
		var day = createTime.slice(6, 8);
		var hour = createTime.slice(8, 10);
		var minute = createTime.slice(10, 12)
		var newTimeStr = year + "-" + month + "-" + day + " " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return createTime;
	}
}

//格式化时间 
//dateTime 需要格式化的时间（格式为：2016-08-05 11:00:00）
// 格式化之后返回时间的格式为：2016年08月05日 11:00
function formatDateTime(dateTime) {
	console.log("dateTime------>" + dateTime);
	if (!dateTime) {
		console.log("时间传入值为空。");
		return;
	}
	if (dateTime.length == 19) {
		var year = dateTime.slice(0, 4);
		var month = dateTime.slice(5, 7);
		var day = dateTime.slice(8, 10);
		var hour = dateTime.slice(11, 13);
		var minute = dateTime.slice(14, 16)
		var newTimeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return dateTime;
	}
}

//格式化时间 服务器返回时间格式为yyyyMMddHHmmssSSS 17位字符串
//将服务器时间修改为yyyy年MM月dd日 HH:mm 的基本格式
//createTime 服务器返回时间
// value 国际化后的时间标志 （年，月，日）
function formatCreateTimeByChina(createTime) {
	if (!createTime) {
		console.log("时间传入值为空。");
		return;
	}
	if (createTime.length > 12) {
		var year = createTime.slice(0, 4);
		var month = createTime.slice(4, 6);
		var day = createTime.slice(6, 8);
		var hour = createTime.slice(8, 10);
		var minute = createTime.slice(10, 12)
		var newTimeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return createTime;
	}
}

/**
 * Description: 加载缓存
 *    后台返回值格式：{"info":[{"codeclass":"XBDM","version":0,"data":[{"code":"1","codedesc":"男"},{"code":"2","codedesc":"女"}]},{"codeclass":"XXDM","version":0,"data":[{"code":"1","codedesc":"A"},{"code":"2","codedesc":"B"}]}]}
 * @param codeclass_arr 将要加载至缓存的codeclass代码组织成数组形式参数
 */
function setCodeMap(codeclass_arr, callback) {
	var url = getRequestAddressUrl("codemap");
	var param_json = {};
	for (var j = 0; j < codeclass_arr.length; j++) {
		param_json[codeclass_arr[j]] = getCodeClassVersion(codeclass_arr[j]);
	}
	var param_str = JSON.stringify(param_json);
	$.ajax({
		type: "POST",
		url: url,
		data: "clv=" + param_str,
		dataType: "json",
		success: function (data) {
			if (data.info != undefined && data.info != null && data.info.length > 0) {
				for (var i = 0; i < data.info.length; i++) {
					var codeClass = data.info[i].codeclass;
					delete data.info[i]["codeclass"];
					store.setItem(codeClass, "{\"data\":" + JSON.stringify(data.info[i].data) + ",\"version\":" + JSON.stringify(data.info[i].version) + "}");
				}
			}
			if (callback != undefined && callback != null) {
				callback();
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			return;
		}
	});
}

//定义字段
var store = window.localStorage;

/**
 * Description:获取codeclass当前缓存版本信息
 * @param codeclass
 * @returns
 */
function getCodeClassVersion(codeclass) {
	var codeclass_json = store.getItem(codeclass);

	if (codeclass_json == undefined) {
		return -1;
	}
	if (typeof codeclass_json == 'string') {
		codeclass_json = eval("(" + codeclass_json + ")");
	}
	if (!codeclass_json.data) {
		return -1;
	}

	return codeclass_json.version;
};

/**
 * Description: 获取codedesc,未找到对应desc返回undefined
 * @param codeclass
 * @param code
 * @returns
 */
function getCodeDescByCodeClass(codeclass, code) {
	if (!code) return code;
	var codes = code.split(",");
	var codeclass_json = store.getItem(codeclass);
	if (!codeclass_json) return code;
	if (typeof codeclass_json == 'string') {
		codeclass_json = eval("(" + codeclass_json + ")");
	}
	var code_arr = codeclass_json.data;
	if (codeclass_json.data == undefined) {
		code_arr = codeclass_json;
	}
	var codesdesc = "";
	for (var i = 0; i < code_arr.length; i++) {
		for (var j = 0; j < codes.length; j++) {
			if (code_arr[i].code == codes[j].replace(/(^\s*)|(\s*$)/g, "")) {
				codesdesc += code_arr[i].codedesc + ",";
			}
		}
	}
	if (codesdesc != "") {
		return codesdesc.substring(0, codesdesc.length - 1);
	} else {
		return code;
	}
};

/**
 * 设置默认头像
 *
 * */
function setDefalutPhoto(value) {
	var photo = "../../../ui/common/images/moren1.png";
	if (!isEmpty(value)) {
		photo = filesHost + value;
	} else {
		photo = "../../../ui/common/images/moren1.png";

	}

	return photo;
}

/**
 * 非空判断
 * 判断传入值是否为 null，undefined，“”,返回true/false
 * */
function isEmpty(value) {
	var flg = false;
	if (value == undefined || value == "" || value == null || value == "none" || value == NaN) {
		flg = true;
	}

	return flg;
}

/**
 * 非空判断
 * 传入数组判断
 * */
function isEmptyArray(value) {
	var flg = false;
	for (var i = 0; i < value.length; i++) {
		if (isEmpty(value[i])) {
			flg = true;
			console.log("入参第" + (i + 1) + "个位空，或不存在");
			break;
		}
	}
	return flg;
}

/**
 * 非空判断
 * 传入数组判断
 * */
function getEmptyIndexByArray(value) {
	var index = -1;
	for (var i = 0; i < value.length; i++) {
		if (isEmpty(value[i])) {
			index = i;
			break;
		}
	}
	return index;
}

/**
 * 网络判断
 * */
function getNetWorkState() {
	var netStateStr = '未知';
	var types = {};
	types[plus.networkinfo.CONNECTION_UNKNOW] = "未知";
	types[plus.networkinfo.CONNECTION_NONE] = "无网络";
	types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
	types[plus.networkinfo.CONNECTION_WIFI] = "WiFi";
	types[plus.networkinfo.CONNECTION_CELL2G] = "2G";
	types[plus.networkinfo.CONNECTION_CELL3G] = "3G";
	types[plus.networkinfo.CONNECTION_CELL4G] = "4G";
	netStateStr = types[plus.networkinfo.getCurrentType()];
	return netStateStr;
};

function isHaveNet() {
	return true;    // 不做检查
	var flg = true;
	var netStateStr = getNetWorkState()
	if (netStateStr == "未知" || netStateStr == "无网络") {
		flg = false;
		mui.toast("请检查网络连接");
	}
	return flg;
}

/***
 *  根据传入的文件类型，返回对应的横版image图标SRC
 * @param {Object} fileType :文件类型
 */
/***
 * 根据传入的文件类型，返回对应的竖版image图标SRC
 */
function getBigIconByType(fileList, position) {
	var fileInfo = fileList[position];
	var gs1 = fileInfo.format;
	return getBigIconByFormat(gs1, fileInfo);
}

function getBigIconByFormat(gs1, fileInfo) {
	var gs = gs1.toLowerCase();
	var src = '../../../ui/common/images/';

	if (gs == "png" || gs == "jpg" || gs == "gif" || gs == "bmp") {
		if (fileInfo) {
			src = fileInfo.address;
			return filesHost + src;
		} else {
			return src + 'file_image.png';
		}
	} else if (gs == 'xls' || gs == 'xlsx') {
		return src + 'file_xls.png';
	} else if (gs == 'flv' || gs == 'swf') {
		return src + 'file_ani.png';
	} else if (gs == 'flash') {
		return src + 'file_flash.png';
	} else if (gs == 'mp3' || gs == 'wma' || gs == 'midi' || gs == 'aac' || gs == 'wav') {
		return src + 'file_audio.png';
	} else if (gs == 'doc' || gs == 'docx') {
		return src + 'file_doc.png';
	} else if (gs == 'ppt' || gs == 'pptx') {
		return src + 'file_ppt.png';
	} else if (gs == 'txt') {
		return src + 'file_txt.png';
	} else if (gs == 'mp4' || gs == 'avi' || gs == 'wma' || gs == 'rmvb' || gs == '3gp' || gs == 'mid') {
		return src + 'file_video.png';
	} else if (gs == 'zip' || gs == 'rar' || gs == 'jar' || gs == 'aar') {
		return src + 'file_zip.png';
	} else if (gs == 'pdf') {
		return src + 'file_pdf.png';
	} else if (gs == '') {
		return src + 'file_other.png';
	} else {
		return src + 'file_other.png';
	}
}

/**
 * 通过文件类型或去文件对应的小图标的方法
 * @param {Object} fileList 文件信息列表
 * @param {Object} position 选中的文件下标
 */
function getSmallIconByType(fileList, position) {
	var fileInfo = fileList[position];

	return getSmallIconByFormat(gs, fileInfo);
}

function getSmallIconByFormat(gs1, fileInfo) {
	var gs = gs1.toLowerCase();
	var src = '../../../ui/common/images/';

	if (gs == "png" || gs == "jpg" || gs == "gif" || gs == "bmp") {
		if (fileInfo) {
			src = fileInfo.address;
			return filesHost + src;
		} else {
			return src + 's_img.png';
		}

	} else if (gs == 'xls' || gs == 'xlsx') {
		return src + 's_xls.png';
	} else if (gs == 'flv' || gs == 'flash' || gs == 'swf') {
		return src + 's_animate.png';
	} else if (gs == 'mp3' || gs == 'wma' || gs == 'midi' || gs == 'aac' || gs == 'wav') {
		return src + 's_audio.png';
	} else if (gs == 'doc' || gs == 'docx') {
		return src + 's_word.png';
	} else if (gs == 'ppt' || gs == 'pptx') {
		return src + 's_ppt.png';
	} else if (gs == 'txt') {
		return src + 's_cource.png';
	} else if (gs == 'mp4' || gs == 'avi' || gs == 'wma' || gs == 'rmvb' || gs == '3gp' || gs == 'mid') {
		return src + 's_video.png';
	} else if (gs == 'zip' || gs == 'rar' || gs == 'jar' || gs == 'aar') {
		return src + 's_zip.png';
	} else if (gs == 'pdf') {
		return src + 's_pdf.png';
	} else if (gs == '') {
		return src + 's_other.png';
	} else {
		return src + 's_other.png';
	}
}

/**
 * 文件上传调用的方法
 */
//传入参数
//files：文件地址数组
//upload_abs_path： "wdcloud-rrt/rest/fileWS/upload"文件服务器上传接口 
//successCallBack:function(data)  上传成功时的回调函数 data参数为服务器返回的json数据
//failCallBack:function(status)  上传失败时的回调函数
//cd  附件的长度
/**
 * @修改时间 2016/09/22 19:20
 * 修改者:zgq
 * 修改内容:增加一个参数:num_i :第几张图片
 * 照片上传修改为多张上传
 */
//var uploadhost = getRequestAddressUrl("filesUploader");
var upload_abs_path = "upload";

var sucess_num = 0;
var fail_num = 0;

function uploadFiles(settings, cd, num_i) {
	if (!settings) {
		console.log("传入参数不存在");
		return;
	}
	;
	//	var w = plus.nativeUI.showWaiting();
	if (!isEmpty(num_i)) {
		if (num_i == cd) {
			mui.toast("正在上传文件...");
		}
	} else {
		mui.toast("正在上传文件...");
	}
	var files = settings.files;
	if (files.length <= 0) {
		plus.nativeUI.alert("没有添加上传文件！");
		return;
	}
	if (settings.upload_abs_path) {
		upload_abs_path = settings.upload_abs_path;
	}
	console.log("hostpath--->>" + uploadhost + upload_abs_path);
	var task = plus.uploader.createUpload(uploadhost + upload_abs_path, {
			method: "POST"
		},
		function (t, status) { //上传完成
			console.log("status->" + status);
			if (status == 200) {
				//				plus.nativeUI.closeWaiting();
				//				plus.nativeUI.toast("上传成功");
				var resp = JSON.parse(t.responseText); // 干些后续处理
				if (settings.successCallBack) {
					settings.successCallBack.call('', resp);
				}
				sucess_num++;
				if ((sucess_num + fail_num) == cd) {
					mui.toast("上传成功:" + sucess_num + ",失败:" + fail_num);
					sucess_num = 0;
					fail_num = 0;
				}
			} else {
				//				plus.nativeUI.closeWaiting();
				//				plus.nativeUI.toast("上传失败：");
				if (settings.failCallBack) {
					settings.failCallBack.call('', status);
				}
				fail_num++;
				if ((sucess_num + fail_num) == cd) {
					mui.toast("上传成功:" + sucess_num + ",失败:" + fail_num);
					sucess_num = 0;
					fail_num = 0;
				}
			}
		}
	);
	for (var i = 0; i < files.length; i++) {
		var f = files[i];
		var path = plus.io.convertAbsoluteFileSystem(f);
		console.log("----filedizhi----------->" + f.toString());
		var length = f.split("/").length - 1;
		var key = f.split("/")[length];
		console.log("fileskey---->>" + key);

		task.addFile(path, {
			key: "files"
		});
		task.addData();
		task.start();
	}
	//	if(task) {
	//		task.start();
	//	} else {
	//		console.log("任务创建失败");
	//	};

}

/**
 *
 * kb转mb
 */
function kBToMB(b) {
	if (isEmpty(b)) { //b shi kong
		return ("0B");
	}
	b = parseInt(b);
	var kb = "";
	var mb = "";
	var gb = "";
	if (b < 1024) { //b
		return (b + "B");
	} else if (b >= 1024 && b < (1024 * 1024)) { //k
		if (b % 1024 == 0) {
			kb = b / 1024;
		} else {
			kb = Math.round(b / 1024);
		}
		return kb + "KB";
	} else if (b >= (1024 * 1024) && b < (1024 * 1024 * 1024)) { //m
		if (b % (1024 * 1024) == 0) {
			mb = b / (1024 * 1024);
		} else {
			mb = Math.round(b / (1024 * 1024));
		}
		return mb + "M";
	} else { //G
		if (b % (1024 * 1024 * 1024) == 0) {
			gb = b / 1024 / 1024 / 1024;
		} else {
			gb = gb + "";
			var i = gb.indexOf(".");
			gb = gb.substring(0, i + 2);
		}
		return gb + "G";
	}
}

/**
 *
 * 四舍五入
 */
function rounding(size) {
	var size = size + "";
	var num = "";
	if (size.length >= 3) {
		var third = size.substring(2, 3);
		size = size.substring(0, 1);
		num = parseInt(size);
		if (third > 5) {
			num = num + 1;
		}
	} else {
		num = parseInt(size);
	}
	return num;
}

/**
 *
 * 年-月-日
 */
function timeFormat(time) {
	var time = time + "";
	if (time == null || time == undefined || time == "") {
		time = ""
		return time;
	}

	if (time.length > 10) {
		time = time.substring(0, 10);
	}
	return time;
}

/**
 * 获取拼接的eq
 * @param {Object} array
 */
function getEqString(myMap) {
	var eqStr = "";

	for (var i = 0; i < myMap.length; i++) {
		if (!isEmpty(myMap[i].text) && !isEmpty(myMap[i].value) && myMap[i].text != "undefined" && myMap[i].value != "undefined") {
			eqStr = eqStr + myMap[i].text + ":" + myMap[i].value + ";";
		}
	}
	if (!isEmpty(eqStr)) { //有值
		eqStr = eqStr.substring(0, eqStr.length - 1);
	}
	return eqStr;
}

/**
 * 入参check
 * @param {Object} jsondate
 */
function checkParams(jsondate) {
	var jsonStr = "{";
	var returnFlag = false;
	for (var x in jsondate) {
		if (jsondate[x] == undefined || jsondate[x] == null) {
			console.log(x + "入参为空");
			returnFlag = true;
		}
	}
	return returnFlag;
}

/**
 * 资源路径的check
 */
function checkZylj(beforeSubStr) {
	var zylj = "";
	if (beforeSubStr.indexOf("http") > -1) {
		zylj = beforeSubStr;
	} else if (beforeSubStr.length > 0) {
		zylj = filesHost + beforeSubStr;
	}
	return zylj;
}

/**
 * 删除原有的list（刷新用）
 */
function removeLi(id) {
	var objUl = document.getElementById(id);

	if (!isEmpty(objUl)) {
		var objLi = objUl.getElementsByTagName("li");
		var length = objLi.length;
		for (var i = 0; i < length; i++) {
			objUl.removeChild(objLi[0]);
		}
	} else {
		mui.toast("刷新失败");
	}
}

function showEle(ele) {
	if (ele.classList.contains("mui-hidden")) {
		ele.classList.remove("mui-hidden");
	}
}

function hiddenEle(ele) {
	if (!ele.classList.contains("mui-hidden")) {
		ele.classList.add("mui-hidden");
	}
}

function hiddenEleByParent(parentEle, targetEle) {
	var eleArr = parentEle.getElementsByTagName(targetEle);
	for (var i = 0; i < eleArr.length; i++) {
		if (!eleArr[i].classList.contains("mui-hidden")) {
			eleArr[i].classList.add("mui-hidden");
		}
	}
}

function isShow(ele) {
	if (ele.classList.contains("mui-hidden")) {
		return false;
	} else {
		return true;
	}
}

function addClass(className, ele) {
	if (!ele.classList.contains(className)) {
		ele.classList.add(className)
	}
}

function deleteClass(className, ele) {
	if (ele.classList.contains(className)) {
		ele.classList.remove(className)
	}
}

/**
 * 错误信息弹窗
 * @param {Object} data
 * @param {Object} code
 */
function toastMesg(data, code1, code2) {
	if (!isEmpty(data)) {
		if (!isEmpty(data.code)) {
			if (code1 > data.code || code2 <= data.code) {
				mui.toast(data.mesg);
			}
		}
	}
}

/**
 *日志打印方法  logFlag控制日志打印
 */
var logFlag = true;

function logText(text) {
	if (logFlag) {
		console.log(text);
	}
}

function formatTimeForTimestamp(timestamp) {
	var date = new Date(timestamp); //获取一个时间对象
	var year = date.getFullYear(); // 获取完整的年份(4位,1970)
	var month = date.getMonth() + 1; // 获取月份(0-11,0代表1月,用的时候记得加上1)
	var day = date.getDate(); // 获取日(1-31)
	var hours = date.getHours(); // 获取小时数(0-23)
	var minutes = date.getMinutes(); // 获取分钟数(0-59)
	var seconds = date.getSeconds(); // 获取秒数(0-59)
	return year + "-" + month + '-' + day;
}

function formatDateTimeForDate(date) {
	var year = date.getFullYear(); // 获取完整的年份(4位,1970)
	var month = date.getMonth() + 1; // 获取月份(0-11,0代表1月,用的时候记得加上1)
	var day = date.getDate(); // 获取日(1-31)
	var hours = date.getHours(); // 获取小时数(0-23)
	var minutes = date.getMinutes(); // 获取分钟数(0-59)
	var seconds = date.getSeconds(); // 获取秒数(0-59)
	return year + "-" + month + '-' + day + " " + hours + ":" + minutes + ":" + seconds;
}

function backWindowChangeColor(color) {
	if (isEmpty(color)) {
		color = "#FFFFFF";
	}
	var currentWebview = plus.webview.currentWebview();
	currentWebview.close();
	plus.navigator.setStatusBarBackground(color);
}

function returnFloat(value) {
	var value = Math.round(parseFloat(value) * 100) / 100;
	var xsd = value.toString().split(".");
	if (xsd.length == 1) {
		value = value.toString() + ".00";
		return value;
	}
	if (xsd.length > 1) {
		if (xsd[1].length < 2) {
			value = value.toString() + "0";
		}
		return value;
	}
}

Array.prototype.remove = function (dx) {
	if (isNaN(dx) || dx > this.length) {
		return false;
	}
	for (var i = 0, n = 0; i < this.length; i++) {
		if (this[i] != this[dx]) {
			this[n++] = this[i]
		}
	}
	this.length -= 1
}

function arrayDelete(array, value) {
	for (var i = 0; i < array.length; i++) {
		if (array[i] == value) {
			array.remove(i);
		}
	}
}

function getLocationPoint(callback) {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(
			function (position) {
				var longitude = position.coords.longitude;
				var latitude = position.coords.latitude;
				callback(longitude, latitude);
				console.log(longitude)
				console.log(latitude)
			},
			function (e) {
				var msg = e.code;
				var dd = e.message;
				console.log(msg)
				console.log(dd)
			}
		)
	} else {
	}
}

//建立一個可存取到該file的url
function getObjectURL(file) {
	var url = null;
	// 下面函数执行的效果是一样的，只是需要针对不同的浏览器执行不同的 js 函数而已
	if (window.createObjectURL != undefined) { // basic
		url = window.createObjectURL(file);
	} else if (window.URL != undefined) { // mozilla(firefox)
		url = window.URL.createObjectURL(file);
	} else if (window.webkitURL != undefined) { // webkit or chrome
		url = window.webkitURL.createObjectURL(file);
	}
	return url;
}

// 定义公共图片上传
function imageUpload(imageView, isUpload, callBack) {
	var imageUploadObj = $('<input class="image-upload" style="display: none" type="file" accept="image/*" />').appendTo('body');

	imageUploadObj.unbind().change(function () {

		let t = $(this);
		let a = t.prop("files")[0];

		let prevUrl = getObjectURL(a);
		imageView.src = prevUrl;

		if (isUpload === false) {
			return callBack(prevUrl, a);
		}

		try {
			var r = new XMLHttpRequest;
			r.open("post", getRequestAddressUrl('base'), true);
			r.setRequestHeader("X-Requested-With", "XMLHttpRequest");
			r.onreadystatechange = function () {
				if (r.readyState == 4) {
					var result = JSON.parse(r.responseText);
					callBack(result);
				}
			};
			var jsonDate = {
				"op": "uploadfile",
				"uid": userInfo.user_id,
				system: systemName
			};
			var i = new FormData;
			i.append("p", JSON.stringify(jsonDate));
			i.append("alert", "1");
			i.append('f', a);
			r.send(i)
		} catch (o) {
			console.log(o);
			alert(o)
		}
	});
	imageUploadObj.click();
}

// 微信自动登录 || 微信登录绑定
let wx_token = localCache('wx_token');
let wx_code = getQueryString('code');

if (inWechat() && !userInfo && !wx_code) {
	// 查询用户信息
	baseApi.get({
		op: 'wechat.login',
		ref: window.location.href
	}, function (result) {
		location.href = result;
	});
} else if (inWechat() && wx_code) {
	// 查询用户信息
	baseApi.post({
		op: 'wechat.getUserInfo',
		wx_code: wx_code,
	}, function (result) {
		localCache('wx_token', result.wx_token);
		if (result.user_info) {
			setLocalUserInfo(result.user_info);
			pageChange("../index/index.html");
		} else {
			checkUserLogin();
		}
	});
} else {
	checkUserLogin();
}